package com.Java.train.business.service.Impl;

import com.Java.train.business.entity.Train;
import com.Java.train.business.entity.TrainCarriage;
import com.Java.train.business.enums.SeatColEnum;
import com.Java.train.business.service.TrainCarriageService;
import com.Java.train.business.service.TrainService;
import com.Java.train.common.response.CommonResp;
import com.Java.train.business.entity.DTO.TrainSeatDTO;
import com.Java.train.business.req.TrainSeatQueryReq;
import com.Java.train.common.response.PageResp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.Java.train.business.entity.TrainSeat;
import com.Java.train.business.mapper.TrainSeatMapper;
import com.Java.train.business.service.TrainSeatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.Java.train.common.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.date.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
/**
* 座位 服务实现类
*
* @author luomoxingchen
* @since 2024-09-22
*/
@Service
public class TrainSeatServiceImpl extends ServiceImpl<TrainSeatMapper, TrainSeat> implements TrainSeatService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainSeatService.class);

    @Autowired
    TrainSeatMapper trainSeatMapper;

    @Autowired
    TrainCarriageService trainCarriageService;

    @Override
    public PageResp<TrainSeatDTO> queryList(TrainSeatQueryReq trainSeatQueryReq){
        // 1.获取当前用户id信息
        //        Long id = LoginMemberContext.getId();
        String trainCode = trainSeatQueryReq.getTrainCode();
        // 2.1查询数据库中是否存在当前信息（id）
        LOG.info("查询页码：{}", trainSeatQueryReq.getPage());
        LOG.info("每页条数：{}", trainSeatQueryReq.getSize());
        PageHelper.startPage(trainSeatQueryReq.getPage(),trainSeatQueryReq.getSize());
        List<TrainSeat> trainSeats = null;
        if(StrUtil.isNotBlank(trainCode)){
            LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<>();
            trainSeats = list(wrapper.eq(TrainSeat::getTrainCode, trainCode));
        }else {
            trainSeats = list();
        }
        if(trainSeats == null || CollUtil.isEmpty(trainSeats)){
            return new PageResp<TrainSeatDTO>();
//            throw new BusniessException(BusniessExceptionEnum.MEMBER_PASSENGER_NOT_EXITS);
        }

        // 3 分析分页信息
        // 3.1 获取分页总条数和页数
        PageInfo<TrainSeat> pageInfo = new PageInfo<>(trainSeats);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // 3.2 转为封装后的返回值并封装到分页返回值中
        List<TrainSeatDTO> list = BeanUtil.copyToList(trainSeats, TrainSeatDTO.class);
        PageResp<TrainSeatDTO> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        // 4.返回查询到的信息
        return pageResp;
    }


    @Override
    public CommonResp<Object> modify(TrainSeat trainSeat) {
        Long id = trainSeat.getId();
        DateTime dateTime = DateTime.now();
        if(ObjectUtil.isNull(id)){
            trainSeat.setId(SnowFlakeUtil.getSnowFlakeNextId());
            trainSeat.setCreateTime(dateTime);
            trainSeat.setUpdateTime(dateTime);
            boolean save = save(trainSeat);
            return new CommonResp<>(save);
        } else {
            trainSeat.setUpdateTime(dateTime);
            boolean update = updateById(trainSeat);
            return new CommonResp<>(update);
        }
    }

    @Override
    public CommonResp<Object> remove(String ids) {
        if(StrUtil.isNotEmpty(ids)){
            String[] array = ids.split(",");
            if(!CollectionUtils.isEmpty(Arrays.asList(array))) {
                return new CommonResp<>(trainSeatMapper.deleteBatchIds(Arrays.asList(array)));
            }
        }
        return new CommonResp<>(Collections.EMPTY_LIST);
    }

    @Override
    public CommonResp<Object> genSeat(String trainCode) {
        // 1.获取seat信息,检查是否生成过
        LambdaQueryWrapper<TrainSeat> wrapper = new LambdaQueryWrapper<>();
        List<TrainSeat> list = list(wrapper.eq(TrainSeat::getTrainCode, trainCode));
        if(CollUtil.isNotEmpty(list) || list != null){
            removeBatchByIds(list);
        }

        // 2.生成车厢总座位数（最后统汇一下）
        Integer sum = 0;
        LambdaQueryWrapper<TrainCarriage> carriageWrapper = new LambdaQueryWrapper<>();
        List<TrainCarriage> carriages = trainCarriageService.list(carriageWrapper.eq(TrainCarriage::getTrainCode, trainCode).orderBy(true, true, TrainCarriage::getIdx));
        for (TrainCarriage carriage : carriages) {
            // 2.1 获取车厢id并查询当前车厢
            Integer carriageIndex = carriage.getIdx();

            // 2.2 获取行数，座次等级，
            LOG.info("当前车厢信息为：{}", carriage);
            Integer lineCount = carriage.getLineCount();
            String seatType = carriage.getSeatType();
            int seatIdx = 1;

            List<SeatColEnum> colList = SeatColEnum.getColsByType(seatType);

            // 2.3 循环每行根据座位等次来生成每个座位
            for(int i = 1; i <= lineCount; i++){
                // 2.3.1 循环列数
                for (SeatColEnum seatColEnum : colList) {
                    DateTime now = DateTime.now();
                    // 2.3.2 生成座位并保存到数据库
                    TrainSeat trainSeat = new TrainSeat();
                    trainSeat.setId(SnowFlakeUtil.getSnowFlakeNextId());
                    trainSeat.setTrainCode(trainCode);
                    trainSeat.setSeatType(seatType);
                    trainSeat.setCarriageIndex(carriageIndex);
                    trainSeat.setCarriageSeatIndex(seatIdx++);
                    trainSeat.setLine(StrUtil.fillBefore(String.valueOf(i), '0', 2));
                    trainSeat.setCol(seatColEnum.getCode());
                    trainSeat.setCreateTime(now);
                    trainSeat.setUpdateTime(now);
                    LOG.info("当前座位信息为：{}", trainSeat);
                    save(trainSeat);
                }
            }
        }
        return new CommonResp<>(true);
    }

}


